package zcatt.ex003.adaptservice;

import org.eclipse.core.runtime.Assert;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.InjectionException;
import org.eclipse.e4.core.internal.services.EclipseAdapter;
import org.eclipse.e4.core.services.adapter.Adapter;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;


public class Activator implements BundleActivator {

	private static BundleContext context;
	private static IEclipseContext localCtx;

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		initializeServices();
	}

	public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;
	}
	
	static IEclipseContext getEclipseCtx()
	{
		return localCtx;
	}
	
	static void initializeServices()
	{
		//以下是自主构建eclipseContext环境.
		IEclipseContext osgiCtx =  EclipseContextFactory.getServiceContext(context);
		Assert.isNotNull(osgiCtx);
		
		localCtx = osgiCtx.createChild();
		Assert.isNotNull(localCtx);
		
		//配置adapter service. 
		//使用EclipseAdapter做为adapter service. EclipseAdapter会使用extP="org.eclipse.core.runtime.adapters"收集的adatapers
		localCtx.set(Adapter.class, ContextInjectionFactory.make(EclipseAdapter.class, localCtx));		
	}
	
	static void injectContext(Object obj)
	{
		ContextInjectionFactory.inject(obj, localCtx);
	}

}
